#!/bin/sh

## java env
export JAVA_HOME=/usr/local/jdk1.8.0_181
export JRE_HOME=$JAVA_HOME/jre

## service name
SERVER_PORT=8080
SERVICE_DIR=/root/chinalife-uums-platform/admin-server
SERVICE_NAME=chinalife-uums-admin
JAR_NAME=$SERVICE_NAME\.jar
PID=$SERVICE_NAME\.pid
cd $SERVICE_DIR

#使用说明，用来提示输入参数
usage() {
    echo "Usage: $0 { start | stop | restart | status}"
    exit 1
}

#检查程序是否在运行
is_exist(){
  P_ID=`ps -ef | grep -w "$SERVICE_NAME" | grep -w "server.port=$SERVER_PORT" | grep -v "grep" | awk '{print $2}'`
  #如果不存在返回1，存在返回0
  if [ -z "${P_ID}" ]; then
   return 1
  else
   return 0
  fi
}

#启动方法
start(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "=== $SERVICE_NAME[$SERVER_PORT] is already running PID=${P_ID}"
  else
    echo "=== Starting $SERVICE_NAME[$SERVER_PORT]..."
    #nohup $JRE_HOME/bin/java -jar $JAR_NAME --server.port=$SERVER_PORT > console.log 2>&1 &
    nohup $JRE_HOME/bin/java -jar $JAR_NAME --server.port=$SERVER_PORT --spring.profiles.active=test > console.log 2>&1 &
    echo $! > $SERVICE_DIR/$PID
    echo "=== Start $SERVICE_NAME[$SERVER_PORT] successed..."
   fi
  }

#停止方法
stop(){
  #is_exist
  pidf=$(cat $SERVICE_DIR/$PID)
  echo "=== Stopping $SERVICE_NAME[$SERVER_PORT]..."
  kill $pidf
  rm -rf $PID
  sleep 2
  is_exist
  if [ $? -eq "0" ]; then
    echo "=== Begin kill $SERVICE_NAME[$SERVER_PORT] -9 $P_ID !!!"
    kill -9  $P_ID
    sleep 2
    echo "=== $SERVICE_NAME[$SERVER_PORT] is not running..."
  else
    echo "=== $SERVICE_NAME[$SERVER_PORT] is not running..."
  fi
}

#输出运行状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "=== $SERVICE_NAME[$SERVER_PORT] is running..."
  else
    echo "=== $SERVICE_NAME[$SERVER_PORT] is not running..."
  fi
}

#重启
restart(){
  stop
  start
}

#根据输入参数，选择执行对应方法，不输入则执行使用说明
case "$1" in
  'start')
    start
    ;;
  'stop')
    stop
    ;;
  'status')
    status
    ;;
  'restart')
    restart
    ;;
  *)
    usage
    ;;
esac
exit 0
